import org.grails.plugins.springsecurity.service.AuthenticateService

import org.springframework.security.providers.UsernamePasswordAuthenticationToken as AuthToken
import org.springframework.security.context.SecurityContextHolder as SCH

/**
 * Actions over User object.
 */
class RegisterController {

	EmailerService emailerService
	AuthenticateService authenticateService
	def daoAuthenticationProvider

	def allowedMethods = [save: 'POST', update: 'POST']

	/**
	 * User Registration Top page
	 */
	def index = {

		if (session.id) {
            log.info("Start User Register");
			def person = new User()
			person.properties = params
			return [person: person]
		}

		redirect(uri: '/')
	}

	/**
	 * Person save action.
	 */
	def save = {

		def person = new User()
		person.properties = params

		def config = authenticateService.securityConfig
		def defaultRole = config.security.defaultRole

		def role = Role.findByAuthority(defaultRole)
		if (!role) {
			person.passwd = ''
			flash.message = 'Default Role not found.'
			render(view: 'index', model: [person: person])
			return 
		}

		if (params.captcha.toUpperCase() != session.captcha) {
			person.passwd = ''
			flash.message = 'Access code did not match.'
			render(view: 'index', model: [person: person])
			return
		}

		if (params.passwd != params.repasswd) {
			person.passwd = ''
			flash.message = 'The passwords you entered do not match.'
			render(view: 'index', model: [person: person])
			return
		}

		def pass = authenticateService.passwordEncoder(params.passwd)
		person.passwd = pass
		person.enabled = true
		person.emailShow = true
		person.description = ''
		if (person.save()) {
			role.addToPeople(person)
			if (config.security.useMail) {
				String emailContent = """You have signed up for an account at:

 ${request.scheme}://${request.serverName}:${request.serverPort}${request.contextPath}

 Here are the details of your account:
 -------------------------------------
 LoginName: ${person.username}
 Email: ${person.email}
 Full Name: ${person.userRealName}
 Password: ${params.passwd}
"""

				def email = [
					to: [person.email], // 'to' expects a List, NOT a single email address
					subject: "[${request.contextPath}] Account Signed Up",
					text: emailContent // 'text' is the email body
				]
      			emailerService.sendEmails([email])
			}

			person.save(flush: true)

            render(view: 'success')
		}
		else {
			person.passwd = ''
			render(view: 'index', model: [person: person])
		}
	}
}
